//
//  RegViewController.m
//  MyShoes
//
//  Created by mac on 11-6-26.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "BangDing_ViewControl.h"
#import "iToast.h"
//#import "CREngine.h"
#import "AppDelegate.h"
#import "GlobalVar.h"
#import "IPDetector.h"
//#import "GYBankCardFormatTextField.h"
@interface BangDing_ViewControl (PrivateMethods)
- (void)initTextField;
@end

@implementation BangDing_ViewControl
@synthesize usernameField;
@synthesize passwordField;
@synthesize repasswordField;
@synthesize tuijianrenField;
@synthesize delegate;

-(void)checkUrlAddress:(int)type Url:(NSString*)url
{
    Request_Type=type;
    net_work=[[NewNetWork alloc]init];
    [net_work setDelegate:self];
    [net_work getNetUrl:url CanShu:nil];
    
}
-(void)viewDidLoad
{
    [super viewDidLoad];
	self.title = @"绑定账号";
    blnRequestBinding = YES;
	[self initTextField];
    dataTableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
	dataTableView.delegate = self;
	dataTableView.dataSource = self;
	//[dataTableView setBackgroundColor:[UIColor whiteColor]];
	dataTableView.scrollEnabled = YES;
	[self.view addSubview:dataTableView];
	UIBarButtonItem *rightButton =[[[UIBarButtonItem alloc]initWithTitle:@"绑定"
																   style:UIBarButtonItemStyleDone
																  target:self action:@selector(dosend:)]autorelease];
	self.navigationItem.rightBarButtonItem = rightButton;
    keFuCall=[[NSUserDefaults standardUserDefaults]objectForKey:@"kefuCall"];
    if (keFuCall)
    {
        UIBarButtonItem *leftButton =[[[UIBarButtonItem alloc]initWithTitle:@"呼叫客服"
                                                                       style:UIBarButtonItemStylePlain
                                                                      target:self action:@selector(CallKeFu)]autorelease];
        self.navigationItem.leftBarButtonItem = leftButton;
    }
    tcpDic1=[[NSMutableDictionary alloc]init];
}
-(void)CallKeFu
{
    UIWebView*callWebview =[[UIWebView alloc] init];
    NSURL *telURL =[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",keFuCall]];// 貌似tel:// 或者 tel: 都行
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    //记得添加到view上
    [self.view addSubview:callWebview];
    [callWebview release];
    
}
-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
    if (keFuCall)
    {
        return @"忘记了密码,请呼叫客服";
    }
    return @"";
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
}

-(IBAction)dosend:(id)dosend
{
    /*
    if (blnRequestBinding==NO)
    {
        return;
    }
     */
    blnRequestBinding = NO;
    if (passwordField.isFirstResponder)
    {
        [self textFieldShouldReturn:passwordField];
    }
    if (repasswordField.isFirstResponder)
    {
        [self textFieldShouldReturn:repasswordField];
    }
    if (usernameField.isFirstResponder)
    {
        [self textFieldShouldReturn:usernameField];
    }
    if (tuijianrenField.isFirstResponder)
    {
        [self textFieldShouldReturn:tuijianrenField];
    }
    if([usernameField.text length] == 0 || [passwordField.text length] == 0 || [repasswordField.text length] == 0)
    {
        iToast *toast = [iToast makeText:@"用户名或密码不能为空!"];
		[toast show];
        return;
    }
    self.nsStrUserPhoneNum = (NSString *)[usernameField.text stringByReplacingOccurrencesOfString:@"-" withString:@""];
    //NSLog(@"====dosend=邦定手机号===:%@",self.nsStrUserPhoneNum);
    BOOL isNum=[self checkTel:self.nsStrUserPhoneNum];
    if (isNum==NO)
    {
        iToast* toast=[iToast makeText:@"请输入正确的手机号码"];
        [toast show];
        return;
    }
	if (![passwordField.text isEqualToString:repasswordField.text])
    {
		iToast *toast = [iToast makeText:@"密码和确认密码不一致!"];
		[toast show];
		return;
	}
    self.nsStrPwd = passwordField.text;
    [self useTheBestUrlToDenglu:[GlobalVar getTheBestUrl] userName:self.nsStrUserPhoneNum password:self.nsStrPwd];
   // NSLog(@"the Bs:%@",BEST_URL);
}
//绑定
-(void)useTheBestUrlToDenglu:(NSString*)theBest userName:(NSString *)name password:(NSString *)pwd
{
    //NSLog(@"========绑定=======");
    HUD = [[[MBProgressHUD alloc] initWithView:self.view]autorelease];
    HUD.removeFromSuperViewOnHide = YES;
    [self.view addSubview:HUD];
    [HUD setLabelFont:[UIFont systemFontOfSize:12]];
    [HUD setLabelText:@"正在绑定,请稍候..."];
    [HUD show:YES];
    //
    //NSString* prepareMD5=[NSString stringWithFormat:@"%@%@%@%@",usernameField.text,SOFT_ID,passwordField.text,@"ysw"];
    NSString* prepareMD5=[NSString stringWithFormat:@"%@%@%@%@",name,SOFT_ID,pwd,@"ysw"];
    NSString* md5Str=[GlobalVar md5Str:prepareMD5];
    startTime=[GlobalVar getTimeChuo];
    ASIFormDataRequest* request;
    if ([GlobalVar sharedInstance].blnUseProxy==YES)
    {
        request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",origin_url_prefix,@"login.php"]]];
        [request setProxyPort:ProxyPort];
        [request setProxyHost:[GlobalVar getTheBestIp]];//
    }else
    {
        request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",theBest,@"proxy.php"]]];
        [request setPostValue:origin_url_prefix forKey:@"apiurl"];
        [request setPostValue:@"login" forKey:@"act"];
    }
    //NSLog(@"绑定 url====:%@",[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",theBest,@"proxy.php"]]);
    [request setDelegate:self];
    [request setTimeOutSeconds:TIME_OUT_SECONDS];
    //[request setPostValue:usernameField.text forKey:@"mobile"];
    //[request setPostValue:passwordField.text forKey:@"password"];
    [request setPostValue:name forKey:@"mobile"];
    [request setPostValue:pwd forKey:@"password"];
    [request setPostValue:@"iphone" forKey:@"platform"];
    [request setPostValue:SOFT_ID forKey:@"softid"];
    [request setPostValue:SOFT_VER forKey:@"version"];
    [request setPostValue:md5Str forKey:@"md5"];
    [request setPostValue:SYSTEM_INFRO forKey:@"model"];
    [request setPostValue:MULTIAGENTSWITCH forKey:@"multiAgent"];
    [request setPostValue:NETWORKSTATE forKey:@"apn"];
    [request setDidFinishSelector:@selector(loginSuccess:)];
    [request setDidFailSelector:@selector(loginFail:)];
    [request startAsynchronous];
}
//原始地址请求回调
-(void)loginSuccess:(ASIHTTPRequest*)request
{
    [HUD hide:YES];
    blnRequestBinding = YES;
    NSString* result=[request responseString];
    NSLog(@"====绑定回调 =======:%@",result);
    endTime=[GlobalVar getTimeChuo];
    UInt64 time_cha=[GlobalVar preRequestTime:startTime AndAfterRequestTime:endTime];
    NSString* loginResult=[NSString stringWithFormat:@"\n%@|%d|%@|login|%@|%@|%@|%llu \n",[GlobalVar getBundleIdentifierAndCurrentDate],[GlobalVar getCarrierNetWorkSignal],[[[[[[request url] absoluteString] componentsSeparatedByString:@"/"] objectAtIndex:2] componentsSeparatedByString:@":"] objectAtIndex:0],SOFT_ID,[GlobalVar getNetWorkStates],self.nsStrUserPhoneNum,time_cha];
    if ([result length]>0)
    {
        //NSLog(@"登录写入记录======:%@",loginResult);
        [GlobalVar writeTheInfoToTheLocal:loginResult];
        NSArray* resultArr=[result componentsSeparatedByString:@"|"];
        NSString* code=[resultArr objectAtIndex:0];
        if ([code isEqualToString:@"1"])//登录成功
        {
            NSString* clientNum=[resultArr objectAtIndex:1];
            NSString* certNum=[resultArr objectAtIndex:2];
            NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
            [defaults setObject:self.nsStrUserPhoneNum forKey:@"LOGIN_USER_KEY"];
            [defaults setObject:self.nsStrPwd forKey:@"LOGIN_USER_PASS"];
            [defaults setObject:clientNum forKey:@"LOGIN_USER_NUMBER"];
            [defaults setObject:certNum forKey:@"CERT_NUM"];
            [defaults synchronize];
            iToast* toast=[iToast makeText:@"登录成功"];
            [toast show];
            if(delegate)
            {
                [delegate bandingSuccess];//appDelegate中代理了BangDing_ViewControl的代理
            }
        }else if([code isEqualToString:@"0"])//错误的提示内容
        {
            iToast* toast=[iToast makeText:[resultArr objectAtIndex:1]];
            [toast show];
        }else
        {
            iToast* toast=[iToast makeText:@"登录失败"];
            [toast show];
        }
    }else
    {
        [GlobalVar writeTheInfoToTheLocal:@"收到数据包为空，重新选线路"];
        [[SocketDispatch sharedInstance] socketCheck];
        [GlobalVar alert:ERRORCODE];
    }

}

-(void)loginFail:(ASIHTTPRequest*)request
{
    [HUD hide:YES];
    blnRequestBinding = YES;
    NSString* time_out_info=[NSString stringWithFormat:@"%@超时 %@",[[[[[[request url] absoluteString] componentsSeparatedByString:@"/"] objectAtIndex:2] componentsSeparatedByString:@":"] objectAtIndex:0],[GlobalVar getBundleIdentifierAndCurrentDate]];
    [GlobalVar writeTheInfoToTheLocal:time_out_info];
    [[SocketDispatch sharedInstance] socketCheck];
    [GlobalVar alert:ERRORCODE];
}

- (BOOL)checkTel:(NSString *)str
{
    if ([str length] == 0)
    {
        return NO;
    }
    NSString *regex = @"^((13[0-9])|(147)|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:str];
    if (!isMatch)
    {
        return NO;
    }
    return YES;
}
-(void)poptoParent
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:self.nsStrUserPhoneNum forKey:@"LOGIN_USER_KEY"];
    [defaults synchronize];
}
-(void)returntoFrontView:(id)sender
{
	[self.navigationController popViewControllerAnimated:YES];
}
//
- (NSInteger)numberOfSectionsInTableView:(UITableView *)aTableView
{
	return 1;
}
- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section
{
	return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *editableCellIdentifier = @"editableCellIdentifier";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
							 editableCellIdentifier];
	if (cell == nil)
    {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
									   reuseIdentifier:editableCellIdentifier] autorelease];
	}
    /*
	UIView *textField = [cell viewWithTag:100];
	if (textField)
    {
		[textField removeFromSuperview];
	}
    */
	int row = [indexPath row];
	if (row == 0) {
		cell.textLabel.text = @"手机号：";
		[cell.contentView addSubview:usernameField];
	}else if (row == 1) {
		cell.textLabel.text = @"密码：";
		[cell.contentView addSubview:passwordField];
	}else if (row == 2){
		cell.textLabel.text = @"确认密码：";
		[cell.contentView addSubview:repasswordField];
	}else if (row == 3){
		cell.textLabel.text = @"推荐人：";
		[cell.contentView addSubview:tuijianrenField];
	}
	cell.selectionStyle = UITableViewCellSelectionStyleNone;
	return cell;
}
-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
/**
 * 初始化TextField
 */
- (void)initTextField
{
    self.usernameField = [[[UITextField alloc]initWithFrame:CGRectMake(95, 10, 200.0, 25.0)]autorelease];
    self.usernameField.delegate=self;
    self.usernameField.placeholder = @"请输入本机号码";
    self.usernameField.keyboardType=UIKeyboardTypeNumberPad;
    self.usernameField.tag = 1000;
    [self.usernameField addTarget:self action:@selector(textFieldValueChanged:)forControlEvents:UIControlEventEditingChanged];

    self.passwordField = [[[UITextField alloc] init] autorelease];
    self.passwordField.frame = CGRectMake(95, 10, 200.0, 25.0);
    self.passwordField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.passwordField.delegate = self;

    self.passwordField.placeholder = @"请输入密码";
    self.passwordField.keyboardType = UIKeyboardTypeNumberPad;
    self.passwordField.secureTextEntry = YES;
		
    self.repasswordField = [[[UITextField alloc] init] autorelease];
    self.repasswordField.frame = CGRectMake(95, 10, 200.0, 25.0);
    self.repasswordField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.repasswordField.returnKeyType = UIReturnKeyDone;
    self.repasswordField.delegate = self;

    self.repasswordField.placeholder = @"请输入确认密码";
    self.repasswordField.keyboardType = UIKeyboardTypeNumberPad;
    self.repasswordField.secureTextEntry = YES;
	
}

-(void) textFieldValueChanged:(UITextField *)sender
{
    int infolenNum = sender.text.length;
    if (count<infolenNum)
    {
        NSMutableString *str = [NSMutableString stringWithFormat:@"%@",sender.text];
        if (infolenNum==4 || infolenNum==9)
        {
            if (![[str substringWithRange:NSMakeRange(3, 1)]isEqualToString:@"-"])
            {
                [str insertString:@"-" atIndex:3];
                sender.text = str;
            }else if(![[str substringWithRange:NSMakeRange(8, 1)]isEqualToString:@"-"])
            {
                [str insertString:@"-" atIndex:8];
                sender.text = str;
            }
            
        }
    }
    count = infolenNum;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	[textField resignFirstResponder];
    /*
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3f];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    dataTableView.frame  = self.view.bounds;
    [UIView commitAnimations];
     */
	return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    /*
    if(dataTableView.frame.size.height !=200)
    {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.3f];
        [UIView setAnimationCurve:UIViewAnimationCurveLinear];
        dataTableView.frame  = CGRectMake(0, 0, 320, 200);
        [UIView commitAnimations];
    }
     */
}
- (BOOL)textField:(UITextField *)textField  shouldChangeCharactersInRange:(NSRange)range   replacementString :(NSString *)string
{
    if (textField.tag == 1000 && range.location==13)
    {
        return NO;
    }else if(range.location==18)
    {
        return NO;
    }
    return YES;
}

- (void)dealloc
{
    //[[CREngine sharedEngine]stop];
    if (tcpRequest!=nil)
    {
        [tcpRequest release];
        tcpRequest=nil;
    }
    [tuijianrenField release];
    [tcpDic1 release];
	[repasswordField release];
	[usernameField release];
	[passwordField release];
	[dataTableView release];
    [super dealloc];
}


@end
